package com.heng.exception;

import com.heng.utils.ResultUtil;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 业务异常处理
    @ExceptionHandler(BusinessException.class)
    public ResultUtil.Result<?> handleBusinessException(BusinessException e) {
        return ResultUtil.error(e.getMessage());
    }

    // 参数校验异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultUtil.Result<?> handleValidationException(MethodArgumentNotValidException e) {
//        String msg = e.getBindingResult().getFieldErrors().stream()
//                .map(FieldError::getDefaultMessage)
//                .collect(Collectors.joining(","));
        return ResultUtil.error(400, "msg :err");
    }

    // 全局异常处理
    @ExceptionHandler(Exception.class)
    public ResultUtil.Result<?> handleException(Exception e) {
        e.printStackTrace();
        return ResultUtil.error("系统异常，请联系管理员");
    }
}

